package com.inco.cloud.common.exception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.inco.cloud.common.model.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

/**
 * 说明：错误异常拦截处理
 * 作者：FH Admin
 * from fhadmin.cn
 */
@Configuration
@Slf4j
public class ExceptionConfiguration implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,Exception ex) {
        log.error("异常: [{}], [{}]", request.getRequestURI(), ex.getMessage(),ex);
        String exInfo = ex.toString().replaceAll("\n", "<br/>");
        MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
        jsonView.setExtractValueFromSingleKeyModel(true);
        ModelAndView mv = new ModelAndView(jsonView);	//返回json
        ReturnT re = new ReturnT();
        if(ex instanceof InvalidGrantException){
            re.setMsg("用户名或密码错误");
            re.setCode(401);
            response.setStatus(HttpStatus.OK.value());
            re.setSuccess(false);
        }else {
            re.setMsg(exInfo);
            re.setCode(600);
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            re.setStatus(600);
            re.setSuccess(false);
        }
        mv.addObject(re);
        return mv;
    }
}
